package com.citycloud.ccuap.tc.admin.config;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.citycloud.ccuap.framework.util.DateUtil;
import com.citycloud.ccuap.tc.admin.constant.OauthErrorEnum;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    final SecurityConfig.SecurityOauth2ClientConfig clientConfig;

    public SecurityAuthenticationEntryPoint(final SecurityConfig.SecurityOauth2ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.error("Spring Securtiy异常", authException);
        putResponse(request, response, OauthErrorEnum.TOKEN_NOT_EXISTS.getDesc(), clientConfig.getUserLogout(), OauthErrorEnum.TOKEN_NOT_EXISTS.getCode());
    }

    private void putResponse(ServletRequest servletRequest, ServletResponse servletResponse, String errorMsg, String url, long code) throws IOException {
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("application/json;charset=UTF-8");
        OutputStream out = servletResponse.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
        String jsonString = getErrorJsonString(errorMsg, url, code);
        pw.println(jsonString);
        pw.flush();
        pw.close();
    }

    private String getErrorJsonString(String message, String url, Long code) {
        String jsonString = "";
        if (message == null) {
            message = "";
        }

        jsonString = "{\"success\":false,\"code\":" + code + ",\"lastTime\":\"" + DateUtil.getDateTimeString(new Date()) + "\",\"message\":\"" + message.replace("'", "\\'") + "\",\"url\":\"" + url + "\"}";
        return jsonString;
    }
}
